package wang.unclecat.testwebview.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ProgressBar;
import ohos.agp.components.webengine.BrowserAgent;
import ohos.agp.components.webengine.WebAgent;
import ohos.agp.components.webengine.WebConfig;
import ohos.agp.components.webengine.WebView;
import ohos.media.image.PixelMap;
import wang.unclecat.droidlib.CatDroid;
import wang.unclecat.testwebview.ResourceTable;

public class MainAbilitySlice extends AbilitySlice {
    private WebView webView;
    private ProgressBar progressBar;
    private Component loadingView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        webView = (WebView) findComponentById(ResourceTable.Id_webview);
        progressBar = (ProgressBar) findComponentById(ResourceTable.Id_progressbar);
        loadingView = findComponentById(ResourceTable.Id_loadingView);

        configWebView();
        webView.load("https://developer.harmonyos.com");
    }

    private void configWebView(){
        WebConfig webConfig = webView.getWebConfig();
        webConfig.setJavaScriptPermit(true);
        webConfig.setDataAbilityPermit(true);
        webConfig.setWebStoragePermit(true);
        webConfig.setViewPortFitScreen(true);
//        webConfig.setLocationPermit(true);
        webView.setWebAgent(new WebAgent() {
            @Override
            public void onLoadingPage(WebView webView, String url, PixelMap icon) {
                super.onLoadingPage(webView, url, icon);
                progressBar.setVisibility(Component.VISIBLE);
                loadingView.setVisibility(Component.VISIBLE);
            }

            @Override
            public void onPageLoaded(WebView webView, String url) {
                super.onPageLoaded(webView, url);
                progressBar.setVisibility(Component.HIDE);
                loadingView.setVisibility(Component.HIDE);
            }
        });
        webView.setBrowserAgent(new BrowserAgent(getContext()){
            @Override
            public void onProgressUpdated(WebView webView, int newValue) {
                super.onProgressUpdated(webView, newValue);
                progressBar.setProgressValue(newValue);
            }
        });
    }

    @Override
    protected void onActive() {
        super.onActive();

        getMainTaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                CatDroid.bringToFront();
            }
        },10);
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
